package com.chat.demo.userservice;

import org.springframework.messaging.simp.user.SimpUserRegistry;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/websocket/status")
public class WebSocketStatus_Controller {

    private final SimpUserRegistry simpUserRegistry;

    public WebSocketStatus_Controller(SimpUserRegistry simpUserRegistry) {

        this.simpUserRegistry = simpUserRegistry;
        System.out.println("✅ WebSocketStatusController 已加载");
    }

    @GetMapping("/users")
    public List<UserInfo> getOnlineUsers() {
        List<UserInfo> users = new ArrayList<>();
        simpUserRegistry.getUsers().forEach(user -> {
            UserInfo info = new UserInfo();
            info.setUsername(user.getName());
            info.setSessions(new ArrayList<>());

            user.getSessions().forEach(session -> {
                SessionInfo sessionInfo = new SessionInfo();
                sessionInfo.setId(session.getId());
                sessionInfo.setSubscriptions(new ArrayList<>());
                session.getSubscriptions().forEach(sub -> {
                    sessionInfo.getSubscriptions().add(sub.getDestination());
                });
                info.getSessions().add(sessionInfo);
            });

            users.add(info);
        });

        return users;
    }

    // 内部类用于返回结构化数据
    private static class UserInfo {
        private String username;
        private List<SessionInfo> sessions;

        public String getUsername() { return username; }
        public void setUsername(String username) { this.username = username; }

        public List<SessionInfo> getSessions() { return sessions; }
        public void setSessions(List<SessionInfo> sessions) { this.sessions = sessions; }
    }

    private static class SessionInfo {
        private String id;
        private List<String> subscriptions;

        public String getId() { return id; }
        public void setId(String id) { this.id = id; }

        public List<String> getSubscriptions() { return subscriptions; }
        public void setSubscriptions(List<String> subscriptions) { this.subscriptions = subscriptions; }
    }
}